package com.andy.buyu.server;

import java.net.InetSocketAddress;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.andy.buyu.server.socket.BuyuServer;


@SpringBootApplication
//@EnableTransactionManagement
public class BuyuApplication implements CommandLineRunner {
	
	@Value("${game.server.port:0}")
	private int port;
	private static boolean gameServerEnable;
	private static BuyuServer buyuServer = null;
	
	public static void main(String[] args) {
		SpringApplication.run(BuyuApplication.class, args);
	}
	
	public static boolean gameServerEnable(){
		return gameServerEnable;
	}

	@Override
	public void run(String... args) throws Exception {
		gameServerEnable = port > 0;
		if(!gameServerEnable())return;
		buyuServer = new BuyuServer();
		InetSocketAddress address = new InetSocketAddress(port);
		
		buyuServer.start(address);

		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				if(buyuServer != null){
					buyuServer.destroy();
				}
			}
		});
	}
	
	public static void destroy(){
		if(buyuServer != null){
			buyuServer.destroy();
			buyuServer = null;
		}
	}
	
}
